<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<%
    String path = request.getContextPath();
%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>会员分组</title>
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/bootcdn/BootCDN/ajax/libs/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="<%=path%>/hplus/css/style.min.css"/>
    <link rel="stylesheet" type="text/css" href="<%=path%>/hplus/css/font-awesome.min93e3.css"/>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.4/themes/default/style.min.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css"
          href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="<%=path%>/hplus/css/plugins/dataTables/css/jquery.dataTables.min.css"/>
    <link rel="stylesheet" type="text/css" href="<%=path%>/hplus/js/plugins/sweetalert/sweetalert2.min.css">
    <style type="text/css">
        body {
            font-size: 14px;
            padding-top: 10px;
        }

        .btn.btn-rounded {
            margin-bottom: 8px;
        }

        .ruleForm {
            width: 100%;
            border-collapse: collapse;
        }

        .ruleForm td {
            border: 1px dashed #ddd;
            padding: 4px;
        }

        .ruleForm select {
            height: 26px;
            width: 80px;
        }

        .ruleForm img {
            cursor: pointer;
        }

        .dataTables_info {
            font-size: 12px
        }

        .dataTables_paginate {
            font-size: 12px;
        }

        table.dataTable thead .sorting:after {
            content: ""
        }

        table.dataTable thead .sorting_desc:after {
            content: ""
        }
    </style>
</head>
<body class="gray-bg">
<div class="container-fluid">
    <div class="row">
        <div class="col-sm-3">
            <div class="ibox">
                <div class="ibox-title" style="padding: 0;">
                    <div style="display:inline-block;width:49%;line-height:44px;border-right: 1px solid #eee;text-align: center;">
                        <shiro:hasPermission name="member_list_group:create_type">
                            <a onclick="func_saveGroup1()">新建分类</a>
                        </shiro:hasPermission>
                    </div>
                    <div style="display:inline-block;width:49%;text-align: center;">
                        <shiro:hasPermission name="member_list_group:create_group">
                            <a href="<%=path%>/view/member/member/group">新建分组</a>
                        </shiro:hasPermission>
                    </div>
                </div>
                <div class="ibox-content">
                    <div class="row">
                        <div class="input-group">
                            <input id="keyword" placeholder="输入名称搜索" type="text" class="form-control"> <span
                                class="input-group-btn">
				            <button onclick="func_searchTree()" type="button"
                                    class="btn btn-primary">搜索</button> </span>
                        </div>
                    </div>
                    <div style="height:1px;border-top: 1px solid #eee;margin: 16px -20px;"></div>
                    <div class="row">
                        <div id="jsTree">
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-9">
            <div class="ibox ">
                <div class="ibox-title">
                    <p>
                        分组名称：<span id="name"></span>&nbsp;&nbsp;&nbsp;&nbsp;
                        本组会员总数：<span id="countTotal"></span>人
                        <!-- 	            		（有邮箱<span id="countEmail"></span>人，有微博昵称<span id="countWeibo"></span>人） -->
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        分组类型：<span id="status"></span>
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <span id="update_time"></span>
                    </p>
                    <div>
                        <table style="width: 100%">
                            <tr>
                                <td>
                                    <shiro:hasPermission name="member_list_group:delete">
                                        <button onclick="func_delGroup()" class="btn btn-primary" type="button">删除分组
                                        </button>
                                    </shiro:hasPermission>
                                    <shiro:hasPermission name="member_list_group:update">
                                        <button onclick="func_selectGroup()" class="btn btn-primary" type="button">
                                            移动到其他分类
                                        </button>
                                    </shiro:hasPermission>
                                    <button onclick="startMarket()" class="btn btn-primary" type="button">发起营销</button>
                                    <shiro:hasPermission name="member_list:export">
                                        <button onclick="func_exportMember(this)" id="exportBtn" class="btn btn-primary"
                                                type="button">导出
                                        </button>
                                    </shiro:hasPermission>
                                    <button onclick="func_refreshMember()" class="btn btn-primary" type="button"
                                            id="refresh_button">刷新
                                    </button>
                                </td>
                                <td>
                                    <div class="input-group">
                                        <input id="phone" placeholder="请输入手机号码" class="form-control">
                                        <span class="input-group-btn">
							            	<button onclick="func_dataTableReload()" type="button"
                                                    class="btn btn-primary">搜索</button>
							            </span>
                                    </div>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
                <div class="ibox-content">
                    <table id="myTable" class="display">
                        <thead>
                        <tr>
                            <th>手机号码</th>
                            <th>姓名</th>
                            <th>等级</th>
                            <th>储值</th>
                            <th>所属门店</th>
                            <th>所属客户代表</th>
                            <th>最近购买时间</th>
                            <th>积分</th>
                        </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/bootcdn/BootCDN/ajax/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.4/jstree.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/artDialog/7.0.0/dialog-plus.js"></script>
<script type="text/javascript" src="<%=path%>/js/memberGroupRule.js"></script>
<script type="text/javascript" src="<%=path%>/js/dateUtils.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.16/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="<%=path%>/js/marketing/jquery.cookie.js"></script>
<script type="text/javascript" src="<%=path%>/js/marketing/dialog.js"></script>
<script src="<%=path%>/hplus/js/plugins/sweetalert/sweetalert2.min.js"></script>

<script type="text/javascript">
    var path = "<%=path%>";
    $.fn.dataTable.ext.errMode = 'none';
    var groupId = getUrlParam("groupId");
    var myDataTable;
    var selectGroupDialog = null;
    var status = 1;
    var exportStatus = 0;	//会员导出状态
    var exportLoop = null;	//会员导出循环器

    $(function () {
        init();
    });

    function init() {
        init_tree();

        $.post(path + "/memberGroup/ajaxGetGroup", {id: groupId}, function (data) {
            if (data.status == "200") {
                var group = data.data;
                $("#name").text(group.name);
                status = group.status;
                if (group.status == 1) {
                    $("#status").text("静态分组");
                    $("#refresh_button").hide();
                } else if (group.status == 2) {
                    $("#status").text("动态分组");
                    $("#refresh_button").show();
                }
                if (group.updateTime == null) {
                    $("#update_time").text("分组创建时间：" + formatDateTimeYMDHMS(group.createTime));
                } else {
                    $("#update_time").text("分组最后刷新时间：" + formatDateTimeYMDHMS(group.updateTime));
                }
                $("#countTotal").text(group.count);
            }
        }, "json");

        if (myDataTable == null) {
            myDataTable = dataTable();
        }
        func_exportStatus();
    }

    function init_tree() {
        $.post(path + "/memberGroup/ajaxGroupTree", function (data) {
            if (data.status != "200") {
                alert("远程请求出错");
                return;
            }
            if ($.jstree.reference('#jsTree') != null) {
                $.jstree.reference('#jsTree').destroy();
            }
            var tree = "";
            tree += "<ul>";
            $.each(data.data, function (i, d) {
                var text1 = "";
                var text2 = d.text;
                if (d.text.length > 5) {
                    text1 = text2;
                    text2 = text1.substr(0, 4) + "...";
                }
                tree += "<li id='" + d.id + "' data-jstree='{\"type\":\"top\"}' title='" + text1 + "'>";
                tree += text2;
                tree += "<ul>";

                $.each(d.children, function (i2, d2) {
                    var text1 = "";
                    var text2 = d2.text;
                    if (d2.text.length > 5) {
                        text1 = text2;
                        text2 = text1.substr(0, 4) + "...";
                    }
                    tree += "<li id='" + d2.id + "' title='" + text1 + "'>";
                    tree += text2;
                });
                tree += "</ul>";
                tree += "</li>";
            });
            tree += "</ul>";
            $("#jsTree").html(tree);

            $("#jsTree").jstree({
                core: {
                    themes: {
                        dots: false
                    },
                    "check_callback": true
                },
                "types": {
                    "default": {
                        "icon": path + "/images/Artboard2.png"
                    },
                    "top": {
                        "icon": path + "/images/Artboard.png"
                    }
                },
                "plugins": ["types", "search", "contextmenu"],
                contextmenu: {
                    items: {
                        <shiro:hasPermission name="member_list_group:update">
                        "rename": {
                            "label": "修改",
                            "action": function (obj) {
                                var inst = jQuery.jstree.reference(obj.reference);
                                var clickedNode = inst.get_node(obj.reference);
                                inst.edit(obj.reference, clickedNode.val, function (new_node) {
                                    var groupId = new_node.id;
                                    var name = new_node.text;
                                    $.post(path + "/memberGroup/ajaxRename", {id: groupId, name: name}, function () {
                                        if (clickedNode.parent != "#") {
                                            $("#name").text(name);
                                        }
                                    });
                                })
                            }
                        },
                        </shiro:hasPermission>
                        <shiro:hasPermission name="member_list_group:delete">
                        "remove": {
                            "label": "删除",
                            "action": function (obj) {
                                var inst = jQuery.jstree.reference(obj.reference);
                                var clickedNode = inst.get_node(obj.reference);
                                if (clickedNode.children.length > 0) {
                                    if (!confirm("您好，删除分类后，分类下属的所有分组将全部删除，是否确认删除？点击“确定”进行删除，点击取消返回页面。")) {
                                        return;
                                    }
                                } else if (clickedNode.parents.length == 2) {
                                    if (!confirm("您好，删除分组后，分组内会员将会全部删除，是否确认删除？点击“确定”进行删除，点击取消返回页面。")) {
                                        return;
                                    }
                                }
                                var temp_groupId = clickedNode.id;
                                var isContains = false;
                                if (groupId == temp_groupId) {
                                    isContains = true;
                                }
                                $.each(clickedNode.children, function (i, d) {
                                    temp_groupId += "," + d;
                                    if (groupId == d) {
                                        isContains = true;
                                    }
                                });
                                $.post(path + "/memberGroup/ajaxDelGroupAll", {groupId: temp_groupId}, function (data) {
                                    if (data.status == "200") {
                                        inst.delete_node(obj.reference);
                                        if (isContains) {
                                            location.href = path + "/view/member/member/group";
                                        }
                                    }
                                }, "json");
                            }
                        }
                        </shiro:hasPermission>
                    }
                }
            }).on("click.jstree", function (e) {
                var nodeId = $.jstree.reference('#jsTree').get_selected()[0];
                var node = $.jstree.reference('#jsTree').get_node(nodeId);
                if (node) {
                    if (node.children.length == 0 && node.parents.length == 2) {
                        var temp_groupId = node.id;
                        if (groupId != temp_groupId) {
                            location.href = path + "/view/member/member/groupList?groupId=" + temp_groupId;
                        }
                    }
                }
            });

            $.jstree.reference('#jsTree').select_node(groupId);
        }, "json");
    }

    function func_searchTree() {
        $("#jsTree").jstree(true).search($.trim($("#keyword").val()));
    }

    //保存分类
    function func_saveGroup1() {
        var d = dialog({
            title: '新建分类',
            content: '<input id="name3" placeholder="请输入分类名称"/>',
            okValue: "保存",
            ok: function () {
                var name = $('#name3').val();
                name = $.trim(name);
                if (name == "") {
                    alert("请输入分类名称");
                    return false;
                }
                var json = {};
                json.name = name;
                json.type = 1;

                $.post(path + "/memberGroup/ajaxGroupSave", json, function (data) {
                    if (data.status == "200") {
                        init();
                    } else {
                        alert("远程请求出错");
                    }
                }, "json");
                this.close();
                this.remove();
            }
        });
        d.show();
    }

    //删除分组
    function func_delGroup() {
        if (confirm("是否删除")) {
            $.post(path + "/memberGroup/ajaxDelGroupAll", {groupId: groupId}, function (data) {
                if (data.status == "200") {
                    location.href = path + "/view/member/member/group";
                }
            }, "json");
        }
    }

    function func_selectGroup() {
        var parentId = $.jstree.reference('#jsTree').get_parent(groupId);
        selectGroupDialog = dialog({
            id: "selectGroupDialog",
            fixed: true,
            padding: 0,
            width: 800,
            height: 240,
            title: '选择分类',
            url: path + "/view/member/member/selectGroup?groupId=" + groupId + "&parentId=" + parentId,
            cancelDisplay: false,
            cancel: function () {
                this.remove();
            }
        });
        selectGroupDialog.showModal();
        $("iframe[name='selectGroupDialog']:visible").attr("scrolling", "auto").css("overflow-x", "hidden").css("overflow-y", "auto");
    }

    function getUrlParam(key) {
        var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }

    function func_refreshMember() {
        if (status == 2) {
            $.post(path + "/memberGroup/ajaxGroupMemberRefresh", {id: groupId}, function (data) {
                if (data.status == "200") {
                    setTimeout(func_dataTableReload, 1600);
                }
            }, "json");
        } else {
            func_dataTableReload();
        }
    }

    function func_dataTableReload() {
        myDataTable.ajax.reload();
    }

    function func_AjaxUrl() {
        return path + "/memberGroup/ajaxGroupPageList";
    }

    function func_columns() {
        var jsonArr = [
            {"data": "phone"},
            {"data": "name"},
            {"data": "crmMemberLevel"},
            {"data": "crmBalance"},
            {"data": "storeName"},
            {"data": "marketName"},
            {"data": "lastCostTime"},
            {"data": "crmScore"}
        ];
        return jsonArr;
    }

    function func_ajaxData() {
        var jsonObject = new Object();
        jsonObject.groupId = groupId;
        if ($.trim($("#phone").val()) != "") {
            jsonObject.phone = $("#phone").val();
        }
        return jsonObject;
    }

    function dataTable() {
        return $('#myTable').DataTable({
            processing: true,
            ordering: false,
            searching: false,
            info: true,
            autoWidth: true,
            lengthChange: false,
            language: {
                emptyTable: '没有数据表',
                info: '从第 _START_ 到第 _END_ 条数据；总共有 _TOTAL_ 条记录',
                infoEmpty: '没有数据',
                lengthMenu: '每页显示 _MENU_ 条记录',
                loadingRecords: '正在加载数据....',
                processing: '正在处理数据....',
                zeroRecords: '没有找到匹配的记录',
                paginate: {
                    first: '首页',
                    previous: '前页',
                    next: '后页',
                    last: '尾页'
                }
            },
            order: [[1, 'desc']],
            pageLength: 10,
            pagingType: 'full_numbers',
            columnDefs: [{
                render: function (data, type, full) {
                    var result = "";
                    if (data != null) {
                        result = data;
                    }
                    return result;
                },
                targets: 0
            }, {
                render: function (data, type, full) {
                    var result = "";
                    if (data != null && data.length > 4) {
                        result = "<span title='" + data + "'>" + data.substr(0, 3) + "..</span>";
                    } else {
                        result = data;
                    }
                    return result;
                },
                targets: 1
            }, {
                render: function (data, type, full) {
                    var result = "";
                    if (data == null) {
                        result = "——";
                    } else {
//					result = data.split(" ")[0];
                        result = data;
                    }
                    return result;
                },
                targets: 2
            }, {
                render: function (data, type, full) {
                    var result = "";
                    if (data == null) {
                        result = "——";
                    } else {
                        result = parseInt(data) / 100;
                    }
                    return result;
                },
                targets: 3
            }, {
                render: function (data, type, full) {
                    var result = "";
                    if (data == null) {
                        result = "——";
                    } else {
                        result = data;
                    }
                    return result;
                },
                targets: 4
            }, {
                render: function (data, type, full) {
                    var result = "";
                    if (data == null) {
                        result = "——";
                    } else {
                        result = data;
                    }
                    return result;
                },
                targets: 5
            }, {
                render: function (data, type, full) {
                    var result = "";
                    if (data == null) {
                        result = "——";
                    } else {
                        var temp = new Date(data);
                        result = temp.getFullYear() + "-" + (temp.getMonth() + 1) + "-" + temp.getDate();
                    }
                    return result;
                },
                targets: 6
            }, {
                render: function (data, type, full) {
                    var result = "";
                    if (data == null || data == '') {
                        result = "0";
                    } else {
                        result = parseInt(data) / 100;
                    }
                    return result;
                },
                targets: 7
            }],
            columns: func_columns(),
            serverSide: true,
            ajax: {
                contentType: 'application/json;charset=utf-8',
                type: 'POST',
                url: func_AjaxUrl(),
                data: function (d) {
                    d.extra_search = func_ajaxData();
                    return JSON.stringify(d);
                }
            }
        });
    }

    //发起营销
    function startMarket() {
        var groupCount = $("#countTotal").text();	//分组总数
        location.href = path + "/view/sms/choseSendObject?type=create&flyGroupId=" + groupId + "&flyGroupCount=" + groupCount;
    }

    /*============================================== 导出分组 ===================================================*/
    function func_exportMember(that) {
        if (exportStatus == "0") {
            $.post(path + "/memberGroup/dealExportMember?groupId=" + groupId, function () {
                func_exportStatus();
            });
        } else if (exportStatus == "1") {

        } else {
            $("#exportBtn").attr("disabled", true);
            var url = path + "/memberGroup/exportMember";
            window.open(url);
            setTimeout(func_exportStatus, 2000);
        }
    }

    //导出状态
    function func_exportStatus() {
        $.post(path + "/memberGroup/exportStatus", function (data) {
            if (data.status == "200") {
                exportStatus = data.data;
                if (data.data == "0") {
                    $("#exportBtn").removeAttr("disabled");
                    $("#exportBtn").text("导出会员")
                } else if (data.data == "1") {
                    $("#exportBtn").text("下载中")
                    if (exportLoop == null) {
                        exportLoop = setInterval(func_exportStatus, 5000);
                    }
                } else {
                    clearTimeout(exportLoop);
                    exportLoop = null;
                    $("#exportBtn").text("下载")
                }
            }
        }, "json")
    }
</script>
</html>